package com.share.device.receiver.processSync;

import com.alibaba.fastjson.JSON;
import com.share.common.rabbit.model.CanalSyncMessage;
import com.share.system.api.domain.Region;
import com.share.system.api.domain.Station;
import com.share.system.api.service.StationRedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
@Slf4j
public class ProcessStationRedisSync {

    @Autowired
    private StationRedisService stationRedisService;

    /**
     *  目前监听只存储主要信息字段到redis中
     *  1. 监听表字段信息
     *  2. 同步关键信息到redis中
     *  3. 其他信息通过id进行查询，然后进行组装
     * @param canalSyncMessage
     * @return
     */
    public boolean processStationRedisSync(CanalSyncMessage canalSyncMessage) {
        try {
            boolean b = false;
            // TODO: 实现具体的业务逻辑处理,写入redis的实现
            if ("INSERT".equals(canalSyncMessage.getType()) || "UPDATE".equals(canalSyncMessage.getType())) {
                /**
                 * 存在问题，Json数据转换问题
                 */
                for (Map<String, Object> data:canalSyncMessage.getData()
                ) {
                    Station station = JSON.parseObject(JSON.toJSONString(data), Station.class);
                    b = stationRedisService.saveStation(station);
                    if ( b){
                        log.info("写入redis成功: {}", b);
                    }else {
                        throw new RuntimeException("写入redis失败");
                    }
                }
            }else if ("DELETE".equals(canalSyncMessage.getType())){
                for (Map<String, Object> data:canalSyncMessage.getData()
                ) {
                    Station station = JSON.parseObject(JSON.toJSONString(data), Station.class);
                    boolean b1 = stationRedisService.removeStation(station.getId());
                    if (b1){
                        log.info("删除redis成功: {}", b1);
                    }else {
                        throw new RuntimeException("删除redis失败");
                    }
                }
            }
            return b;
        } catch (Exception e) {
            log.error("Redis同步站点经纬度信息处理失败: {}", canalSyncMessage, e);
            throw new RuntimeException("Redis同步站点经纬度信息处理失败"+ e.getMessage());
        }
    }

}
